/**
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.aiwei.tdjk.controller;


import com.aiwei.tdjk.common.Constants;
import com.aiwei.tdjk.dto.request.SaleOrderHeaderPagerRequest;
import com.aiwei.tdjk.dto.response.ComparatorMatchHandBookResponse;
import com.aiwei.tdjk.dto.response.MatchHandBookResponse;
import com.aiwei.tdjk.entity.*;
import com.aiwei.tdjk.enums.SaleOrderStatusEnum;
import com.aiwei.tdjk.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.*;

/**
 * <p>User: yanfeng
 * <p>Date: 16-12-13 下午10:15
 * <p>Version: 1.0
 */
@Controller
@RequestMapping("/admin/shangJian")
public class ShangJianController extends BaseController{

    @Autowired
    private DeliveryService deliveryService;

    @Autowired
    private DeliveryDetailService deliveryDetailService;

    @Autowired
    private BookingContainerService bookingContainerService;

    @Autowired
    private SaleOrderHeaderService saleOrderHeaderService;

    @Autowired
    private SaleOrderItemService saleOrderItemService;

    @Autowired
    private CustomsRefinvstdService customsRefinvstdService;

    @Autowired
    private CustomsHandbookService customsHandbookService;

    @Autowired
    private CustomsHandbookProductdetailService customsHandbookProductdetailService;

    @Autowired
    private CustomsHandbookUsedDetailService customsHandbookUsedDetailService;

    protected void setCommonData(Model model) {
        model.addAttribute("statusList", SaleOrderStatusEnum.values());
    }

    @RequestMapping(value = {"/list"}, method = RequestMethod.GET)
    public String list(SaleOrderHeaderPagerRequest request, Model model) {
        request.setOrderType("丰源轮胎海外销售订单");
        setCommonData(model);
        model.addAttribute("page", saleOrderHeaderService.find(request));
        model.addAttribute("saleOrderHeader", request);
        return viewName("list");
    }


    /**
     * 查看发货单对应的商检相关的页面
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "{id}/update", method = RequestMethod.GET)
    public String showUpdateForm(@PathVariable("id") Long id, Model model) {
        model.addAttribute(Constants.OP_NAME, "修改");

        SaleOrderHeader saleOrderHeader = saleOrderHeaderService.get(id);

        model.addAttribute("saleOrderHeader", saleOrderHeader);

        List<SaleOrderItem> saleOrderItems = saleOrderItemService.getListByOrderCode(saleOrderHeader.getSaleordercode());

        model.addAttribute("saleOrderItems", saleOrderItems);

        //转变为海关规格
        HashMap<String,Integer> customsSpecificationsMap = new HashMap();

        for (SaleOrderItem saleOrderItem:saleOrderItems){
            String standard = saleOrderItem.getStandard();
            String customsStandardByInvStandard = customsRefinvstdService.getCustomsStandardByInvStandard(standard);
            if (customsSpecificationsMap.containsKey(customsStandardByInvStandard)){
                int a = customsSpecificationsMap.get(customsStandardByInvStandard)+saleOrderItem.getPlanquty();//todo 计划数量还是打包数量
                customsSpecificationsMap.put(customsStandardByInvStandard,a);
            }else{
                customsSpecificationsMap.put(customsStandardByInvStandard,saleOrderItem.getPlanquty());
            }
        }

        model.addAttribute("customsStandardMap", customsSpecificationsMap);

        Object[] customsStandardValues = customsSpecificationsMap.values().toArray();
        int total=0;
        for (Object o:customsStandardValues){
            total+=((Integer) o);
        }
        //前端显示的数据，规格总量和对应的规格列表
        model.addAttribute("customsStandardValues", customsStandardValues);
        model.addAttribute("customsStandardValuesTotal", total);

        //1、查询可用的手册
        //2、封装对象：是否满足规格需要、满足的数量、可用量的Map集合
        List<CustomsHandbook> customsHandbooks = customsHandbookService.getAllAvailable();

        List<MatchHandBookResponse> matchHandBookList = new ArrayList<>();
        for (CustomsHandbook customsHandbook:customsHandbooks){

            MatchHandBookResponse response = new MatchHandBookResponse();
            response.setCustomerHandBookId(customsHandbook.getId());

            HashMap<String,Integer> map = new HashMap();

            Iterator iter = customsSpecificationsMap.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                Object key = entry.getKey();
                Object val = entry.getValue();
                //根据手册主键、规格，查询手册的具体项目
                CustomsHandbookProductdetail handbookProductdetail = customsHandbookProductdetailService.getByHandBookIdAndSpecifications(customsHandbook.getId(), key.toString());

                //手册有没有这个项目
                int notFrozenCount = 0;
                if (handbookProductdetail==null){
                    response.setFit(false);
                }else {
//                    response.setCustomsHandbookProductdetailId(handbookProductdetail.getId());
                    notFrozenCount = customsHandbookUsedDetailService.getNotFrozenCountByDetailId(handbookProductdetail.getId());
                }
                map.put(key.toString(), notFrozenCount);
                response.setMap(map);
                response.setTotalFitCount(response.getTotalFitCount()+notFrozenCount);
            }
            matchHandBookList.add(response);

        }

        //对手册进行排序  安装手册是否满足和满足的总量
        ComparatorMatchHandBookResponse comparator=new ComparatorMatchHandBookResponse();
        Collections.sort(matchHandBookList, comparator);
        model.addAttribute("matchHandBookList",matchHandBookList);

        //如果商检完成，查看商检的情况:哪个手册占用了哪种规格的手册多少数量
        if (saleOrderHeader.getIsreport()!=null&&saleOrderHeader.getIsreport().equals(true)){
            List<CustomsHandbookUsedDetail> handbookUsedDetails = customsHandbookUsedDetailService.getListBySaleOrderHeaderId(saleOrderHeader.getId());
            model.addAttribute("handbookUsedDetails",handbookUsedDetails);
        }

        return viewName("viewForm");

    }



    /**
     *  确认商检
     * @return
     */
    @RequestMapping(value = "{id}/update", method = RequestMethod.POST)
    public String update(Model model,@PathVariable("id") Long id,Long customerHandBookIdOnlyOne,
                         Integer[] usedCount,RedirectAttributes redirectAttributes) {

        // 判读发货单的状态是否为锁定状态
//        if (delivery.getStatus()!=DeliveryStatusEnum.lock.getCode()){
//            redirectAttributes.addFlashAttribute(Constants.ERROR, "请先锁定或者该发货单已经商检完成！");
//            return redirectToUrl("list");
//        }

        SaleOrderHeader saleOrderHeader = saleOrderHeaderService.get(id);

        model.addAttribute("saleOrderHeader", saleOrderHeader);
        // 判断该手册是否能够满足：消耗的手册数量对比发货单需要的

        List<SaleOrderItem> saleOrderItems = saleOrderItemService.getListByOrderCode(saleOrderHeader.getSaleordercode());

        model.addAttribute("saleOrderItems", saleOrderItems);

        //转变为海关规格
        HashMap<String,Integer> customsSpecificationsMap = new HashMap();

        for (SaleOrderItem deliveryDetail:saleOrderItems){
            String standard = deliveryDetail.getStandard();
            String customsStandardByInvStandard = customsRefinvstdService.getCustomsStandardByInvStandard(standard);
            if (customsSpecificationsMap.containsKey(customsStandardByInvStandard)){
                int a = customsSpecificationsMap.get(customsStandardByInvStandard)+deliveryDetail.getPlanquty();
                customsSpecificationsMap.put(customsStandardByInvStandard,a);
            }else{
                customsSpecificationsMap.put(customsStandardByInvStandard,deliveryDetail.getPlanquty());
            }
        }



        //该手册对应的海关规格的可用量
        HashMap<String,Integer> map = new HashMap();

        Iterator iter = customsSpecificationsMap.entrySet().iterator();
        int j =0;
        while (iter.hasNext()) {


            Map.Entry entry = (Map.Entry) iter.next();
            Object key = entry.getKey();
            Object val = entry.getValue();

            if ((int)val!=usedCount[j]){
                redirectAttributes.addFlashAttribute(Constants.ERROR, "选择的手册数量与需要的数量不一致");
                return redirectToUrl("list");
            }

            //根据手册主键、规格，查询手册的具体项目
            CustomsHandbookProductdetail handbookProductdetail = customsHandbookProductdetailService.getByHandBookIdAndSpecifications(customerHandBookIdOnlyOne, key.toString());
            //手册有没有这个项目
            int notFrozenCount = 0;
            if (handbookProductdetail==null){
            }else {
                notFrozenCount = customsHandbookUsedDetailService.getNotFrozenCountByDetailId(handbookProductdetail.getId());
            }
            map.put(key.toString(), notFrozenCount);
            j++;
        }


        Object[] objects = map.values().toArray();
        for (int i=0;i<objects.length;i++){
            if ((int)objects[i]<usedCount[i]){
                redirectAttributes.addFlashAttribute(Constants.ERROR, "选择的手册不可用，数量不足！");
                return redirectToUrl("list");
            }
        }

        int i=0;
        for (SaleOrderItem saleOrderItem:saleOrderItems){

            String standard = saleOrderItem.getStandard();
            String customsStandardByInvStandard = customsRefinvstdService.getCustomsStandardByInvStandard(standard);
            CustomsHandbookUsedDetail usedDetail = new CustomsHandbookUsedDetail();
            usedDetail.setSpecifications(customsStandardByInvStandard);
//            usedDetail.setDeliveryId(deliveryId);
            usedDetail.setSaleOrderHeaderId(saleOrderHeader.getId());
            //todo 暂且支持一个手册的扣除
            usedDetail.setUsedQty(saleOrderItem.getPlanquty());

            //根据手册主键、规格，查询手册的具体项目
            CustomsHandbookProductdetail handbookProductdetail = customsHandbookProductdetailService.getByHandBookIdAndSpecifications(customerHandBookIdOnlyOne, customsStandardByInvStandard);
            usedDetail.setCustomsHandbookProductdetailId(handbookProductdetail.getId());
            customsHandbookUsedDetailService.add(usedDetail);
            i++;
        }

        //修改发货单状态为：已商检未报关
//        delivery.setStatus(DeliveryStatusEnum.shangjian.getCode());
//        deliveryService.update(delivery);
        saleOrderHeader.setIsreport(true);
        saleOrderHeaderService.update(saleOrderHeader);
        return redirectToUrl("list");

    }


}
